<script setup lang="ts">
import { ref } from "vue";
import type {
  UploadFile,
  UploadRequestHandler,
  UploadRequestOptions
} from "element-plus";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";

/** 图片上传配置 */
const userAccept = ".jpg, .png";
/** 图片上传列表 */
const fileList = ref([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);
const handleRemove = (file: UploadFile) => {
  console.log(file);
  console.log("原本的图片列表");
  fileList.value = [];
};

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!;
  dialogVisible.value = true;
};
const handleDownload = (file: UploadFile) => {
  console.log("要删除的图片");
  console.log(file);
};

const handleChange = () => {
  console.log("原本的图片列表");
};

const handleUpload: UploadRequestHandler = (options: UploadRequestOptions) => {
  console.log("upload");
  const fromData = new FormData();
  fromData.append("image", options.file);
};
</script>

<template>
  <div>
    <el-form-item label="上传图片">
      <el-upload
        v-model:file-list="fileList"
        :auto-upload="true"
        :accept="userAccept"
        list-type="picture-card"
        :limit="1"
        :on-change="handleChange"
        :http-request="handleUpload"
      >
        <el-icon><Plus /></el-icon>
        <!-- 上传图片操作按钮 -->
        <template #file="{ file }">
          <div>
            <img class="object-contain" :src="file.url" alt="" />
            <span class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
              >
                <el-icon><zoom-in /></el-icon>
              </span>
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleDownload(file)"
              >
                <el-icon><Download /></el-icon>
              </span>
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <el-icon><Delete /></el-icon>
              </span>
            </span>
          </div>
        </template>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>
  </div>
</template>

<style lang="scss" scoped></style>
